package org.neusoft.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.mindrot.jbcrypt.BCrypt;
import org.neusoft.dto.UserLogin;
import org.neusoft.dto.UserReg;
import org.neusoft.entity.Users;
import org.neusoft.exception.UserExistException;
import org.neusoft.mapper.UserMapper;
import org.neusoft.service.IUserService;
import org.neusoft.utils.JwtService;
import org.neusoft.vo.UserInfo;
import org.neusoft.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @AUTHOR 尹书岿
 * @DATE 2024/12/18 16:28
 * @DESCRIBE
 */

@Service
public class UserService implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    JwtService jwtService;

    @Override
    public UserInfo register(UserReg userReg) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", userReg.getUser().getEmail());
        Users users = userMapper.selectOne(queryWrapper);
        if (users == null) {
            String password = userReg.getUser().getPassword();
            //注册
            String hashpw = BCrypt.hashpw(password, BCrypt.gensalt());
            Users userEntity = new Users();
            userEntity.setUsername(userReg.getUser().getUsername());
            userEntity.setEmail(userReg.getUser().getEmail());
            userEntity.setPassword(hashpw);
            userMapper.insert(userEntity);

            System.out.println(hashpw);
            UserInfo userInfo = new UserInfo();
            UserVo userVo = new UserVo();
            String token = jwtService.toToken(userEntity.getId().toString());
            userVo.setToken(token);
            userVo.setUsername(userEntity.getUsername());
            userVo.setEmail(userEntity.getEmail());
            userInfo.setUserVo(userVo);
            return userInfo;

        } else {
            throw new UserExistException(6001,"用户已存在");
        }
    }

    @Override
    public UserInfo login(UserLogin userLogin) {
        if (userLogin.getUser() != null) {
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("email", userLogin.getUser().getEmail());
            Users users = userMapper.selectOne(queryWrapper);
            if (users != null) {
                String password = userLogin.getUser().getPassword();
                boolean checkpw = BCrypt.checkpw(password, users.getPassword());
                if (checkpw) {
                    return getUserInfo(users);
                }
            }
        }
        System.out.println("login fail");
        return null;
    }

    private UserInfo getUserInfo(Users users) {
        UserInfo userInfo = new UserInfo();
        UserVo userVo = new UserVo();
        userVo.setToken("");
        userVo.setUsername(users.getUsername());
        userVo.setEmail(users.getEmail());
        userInfo.setUserVo(userVo);
        return userInfo;
    }
}
